import {
  Lifecycle,
  LifecycleEventObserver,
  LifecycleOwner,
  LifecycleState,
  LIFECYCLE_DEFAULT,
  LIFECYCLE_INIT
} from "@duke/component-lifecycle";
import hilog from "@ohos.hilog";
import { VIEW_MODEL_COMPONENT_EVENT_CACHE } from "./Constants";

export abstract class ViewModel {
  clean() {

  }
}

export const BindViewModel: PropertyDecorator = (target: any, propertyKey: string) => {
  if (!target.rerender) {
    hilog.warn(0x0000, 'EventPost', '%{public}s', 'Subscriber current target is not a component');
    return;
  }
  if (!target[VIEW_MODEL_COMPONENT_EVENT_CACHE]) {
    let cache = new Array<string>();
    target[VIEW_MODEL_COMPONENT_EVENT_CACHE] = cache;
    cache.push(propertyKey);
  } else {
    let cache = target[VIEW_MODEL_COMPONENT_EVENT_CACHE] as Array<string>;
    cache.push(propertyKey);
    //不要重复修改原型方向，减少调用堆栈深度
    return;
  }
  if (!target[LIFECYCLE_INIT]) {
    LifecycleOwner(target, LIFECYCLE_DEFAULT);
  }
  let oldFunction = target[LIFECYCLE_INIT];
  target[LIFECYCLE_INIT] = function () {
    let lifecycle: Lifecycle;
    if (!this[LIFECYCLE_DEFAULT]) {
      lifecycle = new Lifecycle();
      this[LIFECYCLE_DEFAULT] = lifecycle;
    } else {
      lifecycle = this[LIFECYCLE_DEFAULT];
    }
    let observer: LifecycleEventObserver = (source, state) => {
      if (state == LifecycleState.ON_DISAPPEAR) {
        let cache = target[VIEW_MODEL_COMPONENT_EVENT_CACHE] as Array<string>;
        cache.forEach(item => {
          (source[item] as ViewModel).clean();
        });
      }
    };
    lifecycle.addObserver(observer);
    oldFunction.apply(this);
  };
}